package com.sixmac.controller;

import com.alibaba.druid.util.HttpClientUtils;
import com.sixmac.ApiConst;
import com.sixmac.core.annotation.Validator;
import com.sixmac.core.base.model.Format;
import com.sixmac.core.constant.ConstCache;
import com.sixmac.core.constant.ConstCacheKey;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.shiro.ShiroKit;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.cache.CacheKit;
import com.sixmac.core.toolbox.kit.RandomKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.ClienUser;
import com.sixmac.service.LoginService;
import com.sixmac.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.UUID;

/**
 * Created by admin on 2018/6/9.
 */
@Controller
public class LoginController extends ApiController {
    @Autowired
    LoginService loginService;

    /**
     * @api {post} /api/login   用户登录  studentId b88888 password 123123
     * @apiName login.login
     * @apiGroup login
     * @apiParam {String}  studentId  学号
     * @apiParam {String} password 密码
     * @apiParam {String} captcha 验证码
     * @apiParam {String} cc app生成的随机字符串（最好唯一），通过这个字符串后台才能知道是哪个用户
     * @apiSuccess {String} user.token token可以是返回的字符串，也可是${id} 比如 ${1}
     * @apiSuccess {String} user.gradeName 班级名称
     * @apiSuccess {String} user.levelName 级别名称
     * @apiError {Integer} 1
     */
    @RequestMapping("/login")
    @Validator(name = {"studentId", "password", "captcha", "cc"}, format = {Format.NOT_NULL, Format.NOT_NULL, Format.NOT_NULL, Format.NOT_NULL})
    public AjaxResult login(String studentId, String password, String captcha, String cc) {
        ClienUser user = Blade.create(ClienUser.class).findFirstBy("studentId =#{studentId}", getCMap().put("studentId", studentId));
        if (!this.verifyCaptcha(cc, captcha)) {
            return error("验证码错误");
        }
        if (user == null) {
            return error("用户不存在");
        }
        if (user.getPassword().equals(password)) {
            String token = UUID.randomUUID().toString();
            user.setIsGuess(isGuess.NO);
            CacheKit.put(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token, user);
            user.setToken(token);
            Map map1 = Db.selectOne("select name from blade_dict where code = 666 and num =" + user.getLevel());
            Map map2 = Db.selectOne("select name from t_class where  id =" + user.getGrade());
            user.setLevelName(Convert.toStr(map1.get("name")));
            user.setGradeName(Convert.toStr(map2.get("name")));
            return json(getData("user", user));
        }
        return error("密码错误");
    }

    /**
     * @api {post} /api/otherLogin   游客登录
     * @apiName login.otherLogin
     * @apiGroup login
     * @apiParam {String}  openId  qq or wecaht openId(任意字符都可以登录)
     * @apiParam {String} type 1 qq 2 wechat
     * @apiSuccess {String} user.token token可以是返回的字符串，也可是${id} 比如 ${1}
     * @apiSuccess {String} user.id 游客是0
     * @apiSuccess {String} user.id 游客是1 非游客是0
     * @apiError {Integer} 1
     */
    @RequestMapping("/otherLogin")
    @Validator(name = {"openId", "type"}, format = {Format.NOT_NULL, Format.NOT_NULL})
    public AjaxResult otherLogin(String openId, Integer type) {
        String token = UUID.randomUUID().toString();
        ClienUser user = new ClienUser();
        if (type == 1) {

        } else {

        }
        user.setId(isGuess.id);
        user.setIsGuess(isGuess.YES);
        CacheKit.put(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token, user);
        user.setToken(token);
        return json(user);
    }

    /**
     * @api {post} /api/generaCaptcha   验证码
     * @apiName login.generaCaptcha
     * @apiGroup login
     * @apiParam {String} cc app生成的随机字符串（最好唯一），通过这个字符串后台才能知道是哪个用户
     * @apiSuccess {String} user.token token可以是返回的字符串，也可是${id} 比如 ${1}
     * @apiSuccess {String} user.id 游客是0
     * @apiSuccess {String} user.id 游客是1 非游客是0
     * @apiError {Integer} 1
     */
    @RequestMapping("/generaCaptcha")
    public AjaxResult generaCaptcha(String cc) {
        // 生成验证码
        String code = RandomKit.randomNumbers(6);
        CacheKit.put(ConstCache.SYS_USER + capcha, cc, code);
        return json(getCMap().put("captcha", code));
    }

    private boolean verifyCaptcha(String studentId, String code) {
        String newCode = CacheKit.get(ConstCache.SYS_USER + capcha, studentId);
        if (newCode == null) {
            return false;
        }
        if (newCode.equals(code)) {
            return true;
        }
        return false;
    }


}
